<?php
/**
 * 类说明 : 连接数据库工具类
 * User: 刘明昆
 * Date: 2019/1/21
 * Time: 8:53
 */
header("Content-Type:text/html;charset=utf-8");
//定义连接数据库的类，并返回链接后的资源
//实现单例模式
//执行普通增删改非返回结果集语句
//执行select语句并可以返回3种类型的数据
//单行结果(一维数组)，多行结果(二维数组)
//单行单例(单个数据)
class mysqlDB{
    public $host;
    public $port;
    public $username;
    public $password;
    public $charset;
    public $dbname;

    //连接结果
    private static $link;

    private $resource;

    //单例方法
    public static function getInstance(){
        if(!isset(self::$link)){
            self::$link = new self();
        }
        return self::$link;
    }

    //禁止new
    private function __construct(){
        $this->host = 'localhost';
        $this->port = '3306';
        $this->username = 'lmk';
        $this->password = '123qwe';
        $this->charset = 'utf8';
        $this->dbname = 'test';

        $this->connect();
        //设定连接编码
        $this->setCharset($this->charset);
        //设定数据库
        $this->selectDb($this->dbname);
    }
    //禁止clone
    private function __clone(){}

    public function connect(){
//        $this->resource = mysql_connect("$this->host:$this->port","$this->username","$this->password") or die("连接数据库失败");
        $this->resource=mysqli_connect("$this->host","$this->username","$this->password","$this->dbname","$this->port") or die("连接数据库失败");
    }
    public function setCharset($charset){
        mysqli_set_charset($this->resource,$charset);
    }
    public function selectDb($dbname){
        mysqli_select_db($this->resource,$dbname);
    }
    /**
     * 执行最基本sql语句
     * @param  返回错误代码
     * @return 返回执行结果
     */
    public function query($sql){
        //执行失败
        if(!$result = mysqli_query($this->resource,$sql)){
            echo "<br/>sql语句".$sql;
            echo "<br/出错信息>".mysqli_error($this->resource);
            echo "<br/出错代码>".mysqli_errno($this->resource);
            die();
        }
        return $result;
    }

    /**
     * 功能执行select语句，返回2维数组
     * 参数:$sql 字符串类型 select语句
     */
    public function getAll($sql){
        $result = $this -> query($sql);
        $arr = array();
        while($rec = mysqli_fetch_assoc($result)){
            $arr[] = $rec;
        }
        return $arr;
    }

    /**
     * 返回影响行数
     *
     */
    public function getupd($sql){
        $this -> query($sql);

        return mysqli_affected_rows($this);
    }
    /**
     * 功能：返回一行数据作为一维数组
     * 参数:$sql 字符串类型 select语句
     */
    public function getRow($sql){
        $result = $this -> query($sql);
        if($rec2 = mysqli_fetch_assoc($result)){
            //如果fetch出来有数据，返回一维数组
            return $rec2;
        }
        return false;
    }

    /**
     * 功能：返回select的第一行第一列
     * 参数:$sql 字符串类型 select语句
     */
    public function getOne($sql){
        $result = $this -> query($sql);
        $rec = mysqli_fetch_row($result);//返回下标为数字的数组
        if($result == false){
            return false;
        }
        return $rec[0];
    }
}

